package com.kingtone.rongji.network;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpStatus;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.kingtone.rongji.biz.LeftCategory;
import com.kingtone.rongji.tool.AppRestClient;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class LeftCategoryRequest extends CommonRequest {

	public void getAllCategory(int type,  final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("type", type);
		params.put("appKey", AppRestClient.API_KEY);
		AppRestClient.get(RongJiRestClient.CATEGORY_ALL_URL, params, new CategoryHandler(restClient));
	}
	
	class CategoryHandler extends BaseJsonHttpResponseHandler {

		private IRequestHandler restClient;

		public CategoryHandler(IRequestHandler restClient) {
			super();
			this.restClient = restClient;
		}
		
		@Override
		public void onFailure(int arg0, Header[] arg1, Throwable throwable, String arg3,
				Object arg4) {
			// TODO Auto-generated method stub
			if (null != throwable) {
				throwable.printStackTrace();
			}
			restClient.onNetworkFailure();
		}

		@Override
		public void onSuccess(int statusCode, Header[] arg1, String responseString, Object arg3) {
			// TODO Auto-generated method stub
			if (statusCode == HttpStatus.SC_OK) {
				try {
					List<LeftCategory> categories = parseResponse(responseString, false);
					if (categories != null) {
						restClient.onBussinessSuccess(categories);
						return;
					}
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			restClient.onNetworkFailure();
		}

		@Override
		protected List<LeftCategory> parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
			// TODO Auto-generated method stub
			Gson gson = new Gson();
			JsonParser parser = new JsonParser();
			JsonElement elment = parser.parse(rawJsonData);
			List<LeftCategory> categories = new ArrayList<LeftCategory>();
			JsonArray jsonArray = elment.getAsJsonArray();
			for (JsonElement jsonObj: jsonArray) {
				LeftCategory category = gson.fromJson(jsonObj, LeftCategory.class);
				categories.add(category);
			}
			return categories;
		}
	}
}
